// 创建右键菜单
chrome.contextMenus.create({
  id: "hx_scanCode",
  type: "normal",
  title: "识别验证码",
  contexts: ["image"],
});
// 识别点击操作
chrome.contextMenus.onClicked.addListener(function (item, tab) {
  if (item.menuItemId == "hx_scanCode") {
    switch_absolute_xpath(item, tab);
  }
});

// 发送消息封装方法
function desktop_notification(msg) {
  chrome.notifications.create("id", {
    type: "basic",
    title: " ", // 这里我故意使显示这个为空，显得没那么拥挤
    message: msg,
    iconUrl: "success.png",
  });
}

// 监听现实消息调用
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.action === "updateStorage") {
    // 更新 storage
    chrome.storage.local.set(
      { [request.data.key]: request.data.val },
      function () {
        console.log("Data saved to storage");
        sendResponse("Data saved");
      }
    );
  }
  if (request.action === "changeConfItem") {
    console.log(request, "requestrequestrequestrequestrequest");
  }
});

function blobToBase64(blobUrl) {
  return new Promise((resolve, reject) => {
    fetch(blobUrl)
      .then((response) => response.blob())
      .then((blob) => {
        const reader = new FileReader();
        reader.onloadend = function () {
          resolve(reader.result);
        };
        reader.readAsDataURL(blob);
      })
      .catch((error) => {
        reject(error);
      });
  });
}

// 点击实现
async function switch_absolute_xpath(info, tab) {
  // console.log(info,tab)
  var src = info.srcUrl; //获取图片对象的src
  if (src.indexOf("blob") != -1) {
    src = await blobToBase64(src);
  }
  let h_x_scan_url = "";
  chrome.storage.local.get("h_x_base_url", function (result) {
    h_x_scan_url = result.h_x_base_url;
  });
  if (!h_x_scan_url) {
    h_x_scan_url = "http://localhost:9911";
  }
  fetch(h_x_scan_url, {
    method: "post",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      src: src,
    }),
  })
    .then((response) => response.text()) // 如果response是json的化，否则调用response.text()
    .then((i) => {
      var text = i;
      chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        if (tabs && tabs.length > 0) {
          var tabId = tabs[0].id;
          chrome.tabs.sendMessage(
            tabId,
            {
              action: "sendContentScan",
              data: {
                text,
              },
            },
            function (response) {
              desktop_notification(response);
              setTimeout(function (e) {
                // 这里的id只要和创建的时候设置id值一样就行了，就可以清理对应id的通知了
                chrome.notifications.clear("id");
              }, 4000);
            }
          );
        }
      });
    });
}
